﻿//
// © Algobox Ltd - Benn Eichhorn
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algobox.Objects.Finance.Assets
{
    public class TickDynamic : ITick
    {
        #region Constructors

        public TickDynamic(string name, IDictionary<decimal, decimal> values)
        {
            Name = name;
            _map = new SortedDictionary<decimal, decimal>(values);
        }

        #endregion

        //////////

        #region Member Variables

        readonly SortedDictionary<decimal, decimal> _map;

        #endregion

        //////////

        #region Properties


        public string Name { get; private set; }


        #endregion

        //////////

        #region Functions

        public decimal Round(decimal price)
        {
            if (_map.Count < 1)
                return price;

            decimal tickSize = _map.LastOrDefault(pair => pair.Key < price).Value;

            if (tickSize == 0m)
            {
                tickSize = _map.First().Value;
            }

            int tickPriceDivisor = (int)(price / tickSize);
            decimal tickModulor = price % tickSize;

            if (tickModulor / tickSize >= 0.5m)
                return (tickPriceDivisor * tickSize) + tickSize;
            else
                return tickPriceDivisor * tickSize;            
        }

        public decimal Round(double price)
        {
            return Round((decimal)price);
        }

        public decimal GetTickSize(decimal price)
        {
            if (_map.Count < 1)
                return price;

            decimal tickSize = _map.LastOrDefault(pair => pair.Key < price).Value;

            if (tickSize == 0m)
            {
                tickSize = _map.First().Value;
            }

            return tickSize;
        }

        public decimal GetTickSize(double price)
        {
            return GetTickSize((decimal)price);
        }

        #endregion

    }
}
